<?php
if (session_id() == '') {
    session_start();
}
require_once ('../classes/gcmClass.php');
require_once ('../classes/LoginClass.php');
require_once ('../classes/ProductDataClass.php');
require_once ('../classes/userClass.php');
require_once ('../utility/appConsts.php');
require_once ('../classes/introClass.php');

$appConstants = new appConstsClass ();
$appConstants->initialize ();
if ($appConstants->DEBUG) {
	echo json_encode ( $appConstants );
}
$control = isset ( $_REQUEST ['controlVar'] ) ? $_REQUEST ['controlVar'] : 'no value';
if ($appConstants->DEBUG) {
	echo 'control var' . $control;
}
if ($control == $appConstants->CONTROL_LOGIN) {
	$username = isset ( $_POST ['username'] ) ? $_POST ['username'] : 'no value';
	$password = isset ( $_POST ['password'] ) ? $_POST ['password'] : 'no value';
	$isWeb = isset ( $_POST ['web'] ) ? $_POST ['web'] : 'no value';
	$result = doLogin ( $username, $password );
	if ($isWeb != 'yesitis') {
	    echo json_encode ( $result );
	}
	$_SESSION ['loggedIn'] = $result ['loggedIn'];
	$_SESSION ['loggedInUserId'] = $result ['loggedInUserId'];
	$_SESSION ['loggedInUserType'] = $result ['loggedInUserType'];
	if ($appConstants->DEBUG) {
		print_r ( $_SESSION );
	}
	if ($isWeb == 'yesitis' && isset($_SESSION) && $_SESSION ['loggedIn'] == 'true') {
		$introPage = new IntroClass ();
		$introPage -> printDashBoard($_SESSION ['loggedInUserId'],$_SESSION ['loggedInUserType']); 
	}
} else if ($control == $appConstants->CONTROL_REG_DEVICE) {
	if ($appConstants->DEBUG) {
		print_r ( $_SESSION );
	}
	$registrationid = isset ( $_POST ['registrationid'] ) ? $_POST ['registrationid'] : 'no value';
	$loggedinuserid = isset ( $_POST ['loggedinuserid'] ) ? $_POST ['loggedinuserid'] : 'no value';
	registerDeviceinDB ( $registrationid, $loggedinuserid );
} else if ($control == $appConstants->CONTROL_GET_DEVICE_DATA) {
	if ($appConstants->DEBUG) {
		print_r ( $_SESSION );
	}
	$headers = apache_request_headers ();
	if ($appConstants->DEBUG) {
		echo "headers <br/>";
		print_r ( $headers );
	}
	$userId = '';
	foreach ( $headers as $Key => $Value ) {
		$str = $Key;
		if (strtolower ( $str ) == 'loggedinuserid') {
			$userId = $Value;
		}
	}
	if ((isset ( $_SESSION ['loggedIn'] ) && $_SESSION ['loggedIn'] == 'true') || $userId != '') {
		$productType = isset ( $_POST ['producttype'] ) ? $_POST ['producttype'] : 'no value';
		$productQty = isset ( $_POST ['productquantity'] ) ? $_POST ['productquantity'] : 'no value';
		$lat = isset ( $_POST ['lat'] ) ? $_POST ['lat'] : 'no value';
		$long = isset ( $_POST ['long'] ) ? $_POST ['long'] : 'no value';
		$userId = $userId != '' ? $userId : $_SESSION ['loggedInUserId'];
		$result = storeProductData ( $productType, $productQty, $userId, $lat, $long );
		$arr = array (
				'iserror' => "" . "$result" 
		);
		echo json_encode ( $arr );
	} else if ($_SESSION ['loggedIn'] == 'false') {
		$arr = array (
				'iserror' => "$appConstants -> LOGINNEEDED" 
		);
		echo json_encode ( $arr );
	}
} else if ($control == $appConstants->CONTROL_SEND_TO_DEVICE) {
	sendMessage ( $messageType );
} else if ($control == $appConstants->CONTROL_SIGNUP) {
	$username = isset ( $_POST ['username'] ) ? $_POST ['username'] : 'no value';
	$password = isset ( $_POST ['password'] ) ? $_POST ['password'] : 'no value';
	$email = isset( $_POST ['email'] ) ? $_POST ['email'] : 'no value';
	$isWeb = isset ( $_POST ['web'] ) ? $_POST ['web'] : 'no value';
	$result = doSignUp ( $username, $password,$email );
	if (!$isWeb) {
	    echo json_encode ( $result );
	}
	if ($isWeb == 'yesitis') {
		if($result['error'] == $appConstants -> USERREGISTEREDSUCCESS) {
			$resultLogin = doLogin ( $username, $password );
			$_SESSION ['loggedIn'] = $resultLogin ['loggedIn'];
			$_SESSION ['loggedInUserId'] = $resultLogin ['loggedInUserId'];
			$_SESSION ['loggedInUserType'] = $resultLogin ['loggedInUserType'];
			if (isset($_SESSION) && $_SESSION ['loggedIn'] == 'true') {
				$introPage = new IntroClass ();
				$introPage -> printDashBoard($_SESSION ['loggedInUserId'],$_SESSION ['loggedInUserType']);
			}
		}
	}
} else if ($control == $appConstants->PRINTPRODUCTDATA) {
	printTestProductData ();
} else if ($control == $appConstants->CONTROL_USERPROFILE) {
	$userid = isset ( $_POST ['userid'] ) ? $_POST ['userid'] : 'no value';
	$oldpassword = isset ( $_POST ['oldpassword'] ) ? $_POST ['oldpassword'] : 'no value';
	$newpassword = isset ( $_POST ['newpassword'] ) ? $_POST ['newpassword'] : 'no value';
	$profileOperation = isset ( $_POST ['profileop'] ) ? $_POST ['profileop'] : 'no value';
	
	doUserProfileChange ( $profileOperation, $userid, $oldpassword, $newpassword );
} else if ($control == $appConstants->PRINTREGID) {
	printTestRegistrationId ();
} else if ($control == $appConstants->CONTROL_GETPRODUCTTYPE) {
	$array = getProductTypeData ();
	echo json_encode ( $array );
} else if ($control == $appConstants->CONTROL_SENDGCM) {
	$messageType = isset ( $_REQUEST ['messagetype'] ) ? $_REQUEST ['messagetype'] : 'no value';
	sendMessage ( $messageType );
} else if ($control == $appConstants->CONTROL_ADDPRODUCT) {
	$userType = isset ( $_REQUEST ['usertype'] ) ? $_REQUEST ['usertype'] : 'no value';
	$productType = isset ( $_REQUEST ['producttype'] ) ? $_REQUEST ['producttype'] : 'no value';
	$arr = '';
	if ($userType == $appConstants->USERTYPE_ADMIN) {
		$result = addProductViaAdmin ( $userType, $productType );
		$arr = '';
		if ($result == 1) {
		$arr = array (
				'data addition' => "" . "$result"
		);
		} else {
			$arr = array (
					'not successful' => "" . "-1"
			);
		}
	}
	echo json_encode ( $arr );
} else if ($control == $appConstants->CONTROL_CHANGEROLES) {
	$result = getUserData();
	$arr = array("data"=>$result);
	echo json_encode ( $arr );
} else if ($control == $appConstants->CONTROL_USERTYPECHANGE) {
	$jsonStr = file_get_contents('php://input');
 	$fArr = array("data"=>$jsonStr);
	if ($appConstants->DEBUG) {
		print_r(json_encode($fArr));
	}
 	$resultArr = updateUserType(json_encode($fArr));
 	$response = array("result"=>$resultArr);
 	print_r(json_encode($response));
} else if ($control == $appConstants->CONTROL_SEARCHUSEREMAIL) {
	// TODO: go into user class search username of person if found return in json
	$email = isset( $_POST ['searchemail'] ) ? $_POST ['searchemail'] : 'no value';
	if ($email != 'no value') {
		$user = new User ();
		$introPage = new IntroClass ();
		$arr = $user -> getSearchedUserDataFromUserTable($email);
		$count = count($arr);
		if ($count == 1) {
			$introPage -> userName = $arr[0]['username'];
		    $introPage -> printNextPageWithRelevantScreen(211);
		} else if ($count < 1){
			$introPage -> printNextPageWithRelevantScreen(311);
		} else if ($count > 1) {
			// more than one account presnt with same email address not possible
		}
	} 
} else if ($control == $appConstants->CONTROL_LOGOUT) {
	if (isset($SESSION['loggedIn']) && $SESSION['loggedIn'] == 'true'  ) {
		$SESSION['loggedIn'] = 'false';
		unset($SESSION['loggedIn']);
	}
	if (isset($SESSION['loggedInUserId'])) {
		$SESSION['loggedInUserId'] = '-1';
		unset($SESSION['loggedInUserId']);
	}
	if (isset($SESSION['loggedInUserType'])) {
		$SESSION['loggedInUserType'] = 'false';
		unset($SESSION['loggedInUserType']);
	}
	session_destroy();
	header("Location:../view/");
}

// function definitions
function doUserProfileChange($profileOperation, $userid, $oldpassword, $newpassword) {
	$user = new User ();
	if ($profileOperation == "1") {
		$resultArr = $user->editUser ( $userid, $oldpassword, $newpassword );
		echo json_encode ( $resultArr );
	}
}

function getUserData() {
	$user = new User ();
	
	return $user->getUserDataFromUserTable ();
	
}

function doSignUp($username, $password,$email) {
	$loginProcess = new Login ();
	return $loginProcess->performUserRegistration ( $username, $password,$email );
}
function doLogin($username, $password) {
	$loginProcess = new Login ();
	return $loginProcess->performLogin ( $username, $password );
}
function registerDeviceinDB($registrationid, $loggedinuserid) {
	if ($registrationid != 'no value' && $loggedinuserid != 'no value') {
		$gcm = new GCM ();
		$arr = $gcm->registerDeviceAtServer ( $registrationid, $loggedinuserid );
		echo json_encode ( $arr );
	}
}
function getDataFromDevice($regsitrationId, $lat, $long, $time) {
	if ($regsitrationid != 'no value' && $lat != 'no value' && $long != 'no value' && $time != 'no value') {
		$gcm = new GCM ();
		$gcm->getDataFromDevice ( $regsitrationid, $lat, $long, $time );
	}
}
function storeProductData($productType, $productQty, $userId, $lat, $long) {
	$prdata = new ProductData ();
	return $prdata->storeProductData ( $productType, $productQty, $userId, $lat, $long );
}
function getProductTypeData() {
	$prdata = new ProductData ();
	return $prdata->getProductTypeData ();
}
function sendMessage($messageType) {
	if ($messageType != 'no value') {
		$gcm = new GCM ();
		$result = $gcm->sendMessageToDevice ( $messageType );
	}
}
function printTestProductData() {
	$prdata = new ProductData ();
	$prdata->printTestProductData ();
}
function printTestRegistrationId() {
	$prdata = new ProductData ();
	$prdata->printTestRegistrationId ();
}
function addProductViaAdmin($userType, $productType) {
	$prdata = new ProductData ();
	return $prdata->addProduct ( $productType );
}

function updateUserType($json_str) {
	$user = new User ();
	
	return $user->updateUserTypeWithJSONString($json_str);
}

?>